use salvo::{handler, Request};
use crate::domain::dto::{rbatis_to_res, Res, ResObj, PageRes};
use crate::domain::dto::user_dto::{UserCreateRequest};
use crate::domain::entity::user_entity::UserEntity;
use crate::domain::error::AccountError;
use crate::service::user_service;

/// user_register 用户注册
#[handler]
pub async fn user_add(request: &mut Request) -> Res<bool> {
    let param = request.parse_json::<UserCreateRequest>()
        .await
        .map_err(|err| {
            println!("{}", err);
            ResObj::fail_with_error(AccountError::RequestError)
        })?;
    let res = user_service::create_user(param).await;
    rbatis_to_res(res)
}

/// page_list 用户分页
#[handler]
pub async fn page_list(request: &mut Request) -> Res<PageRes<UserEntity>> {
    let page = request.query::<u64>("page").unwrap_or(1);
    let limit = request.query::<u64>("limit").unwrap_or(10);
    let user_type = request.query::<u8>("user_type");
    let user_name = request.query::<String>("username");
    tracing::info!("用户分页查询 [页码:{},页大小{},用户类型:{:?},用户名称:{:?}]", page, limit, user_type, user_name);
    let res = user_service::user_page(page, limit, user_type, user_name).await;
    rbatis_to_res(res)
}

/// user_delete 用户删除
#[handler]
pub async fn user_delete(req: &mut Request) -> Res<String> {
    let id_option = req.query::<u64>("id");
    if id_option.is_none() {
        return Err(ResObj::fail_with_error(AccountError::RequestError));
    }
    let res = user_service::user_delete(id_option.unwrap()).await;
    rbatis_to_res(res)
}

// #[handler]
// pub async fn update_password(req: &mut Request) -> Res<PageRes<UserEntity>> {
//     // todo!()
// }